package com.augurit.wf.common.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.dozer.DozerBeanMapper;
import org.jbpm.api.JbpmException;
import org.jbpm.api.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.augurit.wf.bi.service.IWfBusInstanceService;
import com.augurit.wf.bi.web.form.WfBusInstanceTaskForm;
import com.augurit.wf.client.summary.service.IWfTaskSummaryService;
import com.augurit.wf.common.constant.WfConstant;
import com.augurit.wf.common.form.WfBusBaseEntity;
import com.augurit.wf.common.service.IWfBusClientService;
import com.augurit.wf.common.service.IWfService;
import com.augurit.wf.common.util.WfUtils;

@Transactional
public abstract class WfBusClientServiceImpl<T extends WfBusBaseEntity> implements IWfBusClientService<T> {

	@Autowired
	private IWfBusInstanceService wfBusInstanceService;
	
	@Autowired
	private IWfService wfService;
	
	
	public WfBusInstanceTaskForm wfBusSave(final T form, final boolean isNewForm, final String masterEntity, final String templateCode, final Long taskInstDbid, final String startWfUserKey) {
		if(form != null && templateCode != null && templateCode.trim().length() > 0 && form != null
				&& startWfUserKey != null && startWfUserKey.trim().length() > 0){

			//保存业务处理
			this.save(form);
			
			//业务校验
			if(form.getId() == null)
				throw new JbpmException("错误原因：主业务实体主键为空！");		
			
			
			//流程变量处理，默认将主业务对象作为form变量
			Map<String, Object> params = new HashMap<String, Object>();
			params.put(WfConstant.VAR_MASTER_ENTITY_ALIAS, form);
					
			//流程处理
			if(isNewForm){
				return wfService.wfBusStart(templateCode, form, startWfUserKey, params);
			}else{
				wfBusInstanceService.syncSummary(masterEntity, form.getId().toString(), form);					//同步汇总信息
				wfService.getProcessEngine().getTaskService().setVariables(taskInstDbid.toString(), params);	//同步流程变量
				return WfUtils.getCurTaskInfo(form.getId().toString(), taskInstDbid);
			}
		}
		
		return null;
	}
}
